import os 
import shutil
import openslide 
import numpy as np 
import cv2
import xml.etree.ElementTree as ET
import tqdm
import threading
import copy
path=r'/media/alex/FA5EB5A15EB556DB/uterus/2023.12.28 子宫内膜标注'
spath=r'innotation_from_prediction'
def draw(pointlist, w,h ,color = 255,im = None):
    if im is None:
        im=np.zeros((w,h),dtype='uint8')
    # print(img1.shape[:2])
    if len(pointlist) > 0:
        for points in pointlist:
            # print(points)
            point=np.array(points,np.int32)
                # print(point)
            # print([point])
            # cv2.polylines(im,[point],1.5,255)
            # cv2.polylines(im, [point], True, 255, thickness=1)
            # # 绘制一个多边形
            cv2.fillPoly(im,[point],color)
            # print (im.shape,np.sum(im))
    return im

def edge_detect(img,tile_size):
    if np.sum(img[0,:])==0 and np.sum(img[tile_size-1,:])==0 and np.sum(img[:,0])==0 and np.sum(img[:,tile_size-1])==0:
        return True
    print(np.sum(img[0,:]),np.sum(img[tile_size-1,:]),np.sum(img[:,0]),np.sum(img[:,tile_size-1]))
    return False


def process_and_save_image(slide,index_x,index_y,tile_size,im):
    region = slide.read_region((index_y, index_x), 0, (tile_size, tile_size))
    simg2=os.path.join(s2t,'{}_{}.png'.format(index_x,index_y))
    cv2.imwrite(simg2,im)
    simg1=os.path.join(s2,'{}_{}.png'.format(index_x ,index_y ))
    print(simg1)
    region.save(simg1)


for i in tqdm.tqdm(os.listdir(path)):
    # print (i)
    if i.endswith('xml'):
        path1=os.path.join(path,i)
        s1=os.path.join(spath,i.split('\\')[-1][:-4])
        if not os.path.exists(s1):
            os.makedirs(s1)
        train=i.split('\\')[-1][:-4]+'.ndpi'
        # print(i,img)
        # print(s1)
        img=os.path.join(path,train)
        mask=os.path.join(path,i)
        s2=os.path.join(s1,'train')
        s2t=os.path.join(s1,'trainmask')
        if os.path.exists(s2):
            shutil.rmtree(s2)
        if os.path.exists(s2t):
            shutil.rmtree(s2t)
        os.makedirs(s2)
        os.makedirs(s2t)
        # print(img,mask)
        # print(s2)
        slide = openslide.open_slide(img)
        width, height = slide.dimensions
#         # print(slide.dimensions)
#     # # # 定义每个小病理切片的大小
        tree = ET.parse(path1)
        root = tree.getroot()
        
        annotation1 =  list(root.iter('Annotation'))[0]


        # draw cells
        po_list=[]
        for region in annotation1.iter('Region'):
            list1=[]
            for vertex in region.iter('Vertex'):
                x = vertex.get('X')
                y = vertex.get('Y')
                list1.append([int(x),int(y)])
            po_list.append(copy.deepcopy(list1))
        Mask=draw(po_list,width, height,color=255 )

        # # draw nucleus
        # try:     
        #     annotation2 =  list(root.iter('Annotation'))[1] 
        #     po_list=[]
        #     for region in annotation2.iter('Region'):
        #         list1=[]
        #         for vertex in region.iter('Vertex'):
        #             x = vertex.get('X')
        #             y = vertex.get('Y')
        #             list1.append([int(x),int(y)])
        #         po_list.append(list1)
        #     Mask=draw(po_list,width, height,color=127,im=Mask )        
        # except:
        #     print (i,'no annotation2')
        #     pass

        tile_size = 1024
        index_x = 0
        index_y = 0
        threads = []
        while True:

            while True:

            
                # 获取当前小病理切片的区域
                
                while True:
                    # print (index_x,index_y,width,height)
                    im=Mask[index_x:index_x+tile_size,index_y:index_y+tile_size]
                    if np.sum(im)==0:
                        break
                    if edge_detect(im,tile_size):
                        t = threading.Thread(target=process_and_save_image,args=(slide,index_x,index_y,tile_size,im))
                        t.start()
                        threads.append(t)
                        break
                    else:
                        index_y+=100
                        index_x+=100
                        if (index_x +tile_size > width ):
                            break
                # im=Mask[index_x:index_x+tile_size,index_y:index_y+tile_size]
                # if np.sum(im)!=0:
                #     region = slide.read_region((index_y, index_x), 0, (tile_size, tile_size))
                #     simg2=os.path.join(s2t,'{}_{}.png'.format(index_x,index_y))
                #     cv2.imwrite(simg2,im)
                #     simg1=os.path.join(s2,'{}_{}.png'.format(index_x ,index_y ))
                #     print(simg1)
                #     region.save(simg1)
                
                index_x += tile_size
                if (index_x +tile_size > width ):
                    index_x=0
                    break
            index_y += tile_size
            if (index_y + tile_size > height ):
                break
        for t in threads:
            t.join()
        slide.close()
            

# print(Mask)
# num=(45,52)
        # for i in range(0, Mask.shape[1], tile_size):
        #     for j in range(0, Mask.shape[0], tile_size):
        #         simg2=os.path.join(s2t,'{}_{}.png'.format(i,j))
        #         im=Mask[j:j+tile_size,i:i+tile_size]
        #         cv2.imwrite(simg2,im)
        # i1=i.split('.')[0]+i.split('.')[1]+i.split('.')[2]
        # s1=os.path.join(spath,i1)
        # ndp=os.path.join(path1,i)
        # print(ndp)
        # if not os.path.exists(s1):
        #     os.makedirs(s1)
        # celltpath=os.path.join(s1,'train')
        # celltpathmask=os.path.join(s1,'trainmask')
        # if not os.path.exists(celltpath):
        #     os.makedirs(celltpath)
        # if not os.path.exists(celltpathmask):
        #     os.makedirs(celltpathmask)
        # print(celltpath)
        # print(s1)
        # img=i1+'.npdi'
        # is1=os.path.join(path,img)
        # print(is1)